package com.only4play.usercenter.process;

import com.only4play.usercenter.model.RequestLog;
import com.only4play.usercenter.service.RequestLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author liyuncong
 * @version 1.0
 * @file RequestLogQueueProcess
 * @brief 请求日志队列处理
 * @details 请求日志队列处理
 * @date 2024-05-21
 *
 * Edit History
 * ----------------------------------------------------------------------------
 * DATE                     NAME               DESCRIPTION
 * 2024-05-21               liyuncong          Created
 */

@Slf4j
public class RequestLogQueueProcess {

    /**
     * 日志入库单次提交数量
     */
    private static final int LOG_MAX_COMMIT = 500;

    private final ExecutorService executorService = new ThreadPoolExecutor(
        1,
        1,
        0L,
        TimeUnit.MILLISECONDS,
        new LinkedBlockingQueue<>(1024),
        new LogThreadFactory("LogQueue-pool"));

    @Autowired
    private RequestLogService<RequestLog> requestLogService;


    /**
     * 消费日志
     */
    @Scheduled(fixedDelay = 3000)
    public void processLog() {
        executorService.execute(() -> {
            int idx = 0;
            List<RequestLog> logs = new ArrayList<>();
            while (!requestLogService.isEmpty() && idx < LOG_MAX_COMMIT) {
                logs.add(requestLogService.poll());
                idx++;
            }

            if (!CollectionUtils.isEmpty(logs)) {
                log.info("批量插入请求日志，数量:{}", logs.size());
                requestLogService.insertBatch(logs);
            }
        });
    }
}

